package com.example.picturebacked.api.aliyunai;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.example.picturebacked.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.example.picturebacked.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.example.picturebacked.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.example.picturebacked.exception.BusinessException;
import com.example.picturebacked.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Autheor LBT
 */
@Slf4j
@Component
public class AliYunAiApi {
    // 读取配置文件
    @Value("${aliYunAi:key}")
    private String apiKey;

    // 创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    // 获取任务地址
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建任务
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        if (createOutPaintingTaskRequest == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "扩图参数为空");
        }
        /**
         * 根据官方文档输入请求头
         * curl --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting' \
         * --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
         * --header 'X-DashScope-Async: enable' \
         * --header 'Content-Type: application/json' \
         * --data '{
         *     "model": "image-out-painting",
         *     "input": {
         *         "image_url": "http://xxx/image.jpg"
         *     },
         *     "parameters":{
         *         "angle": 45,
         *         "x_scale":1.5,
         *         "y_scale":1.5
         *     }
         * }'
         */
        // 发送请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header("Authorization", "Bearer " + apiKey)
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        try (HttpResponse httpResponse = httpRequest.execute()) {
            // 接收返回值并自动关闭链接，想要设置这种自动关闭，必须调用的接口实现了AutoCloseable接口
            if (!httpResponse.isOk()) {
                log.error("请求异常：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图失败");
            }
            CreateOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            // 只要code有值就表示失败
            String errorCode = response.getCode();
            if (StrUtil.isNotBlank(errorCode)) {
                String errorMessage = response.getMessage();
                log.error("AI 扩图失败,errorCode:{},errorMessage{}", errorCode, errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图失败," + errorMessage);
            }
            return response;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取请求结果失败");
        }
    }

    /**
     * 查询创建的任务
     * <p>
     * taskId 任务ID
     */
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务ID不能为空");
        }
        // 通过加入任务ID，查询任务，并自动关闭Http链接
        try (HttpResponse httpResponse = HttpRequest
                .get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header("Authorization", "Bearer " + apiKey)
                .execute()) {
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取请求结果失败");
            }
            return JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
        }
    }
}






























